'use strict'

function parseCPULimit(detail) {
  if (!detail.cpus || !detail.cpuset || !detail.cpuset.effective) return ''

  let cpus = detail.cpus

  let elength = detail.cpuset.effective.length
  let ecpus = detail.cpuset.effective

  if (elength === 1) return ''

  if (cpus[0] === '%') {
    let cp, pos = 'rand'
    
    if (['-', '+', '='].indexOf(cpus[cpus.length - 1]) >= 0) {
      cp = parseInt(cpus.substring(1, cpus.length - 1))
      pos = cpus[cpus.length - 1]
    } else {
      cp = parseInt(cpus.substring(1))
    }
    
    if (isNaN(cp)) return ''

    if (cp <= 0 || cp >= 100) return ''

    cp = cp / 100

    let ind = 0
    switch (pos) {
      case 'rand':
        ind = parseInt(Math.random() * (elength - elength * cp))
        return ecpus.slice(ind, parseInt(elength * cp) + ind)
        break
      
      case '=':
        ind = parseInt(elength / 2) - parseInt(elength * cp / 2)
        return ecpus.slice(ind, ind + parseInt(elength * cp + 0.5))
        break

      case '-':
        ind = 0
        return ecpus.slice(ind, parseInt(elength * cp + 0.2))
        break

      case '+':
        let total = parseInt(elength * cp + 0.1)
        let real_cpus = []
        let count = 0
        for (let i = elength-1; i >= 0; i--) {
          real_cpus.push(ecpus[i])
          count++
          if (count >= total) break
        }
        return real_cpus
    }
    
  }

  return cpus
}

let arr = [
  {
    cpus: '%50+',
    cpuset: {
      effective: [0,1,2,3,4,5,6,7,8,9,10,11,12]
    }
  },

  {
    cpus: '%80=',
    cpuset: {
      effective: [0,1,2,3,4,5,6,7,8,9,10,11,12]
    }
  },

  {
    cpus: '%90-',
    cpuset: {
      effective: [0,1,2,3,4,5,6,7,8]
    }
  },

  {
    cpus: '%60+',
    cpuset: {
      effective: [0,1]
    }
  },

  {
    cpus: '%60=',
    cpuset: {
      effective: [0,1,2,3]
    }
  },

  {
    cpus: '%60+',
    cpuset: {
      effective: [0,1,2,3,4]
    }
  },

  {
    cpus: '%70=',
    cpuset: {
      effective: [0,1,2,3,4,5,6]
    }
  },

  {
    cpus: '%70',
    cpuset: {
      effective: [0,1,2,3,4,5,6,7]
    }
  },


]

for (let a of arr) {
  console.log(a, parseCPULimit(a))
}
